<template>
  <div class="users-box">
    <mianbaoxie name1="用户管理" name2="用户列表"></mianbaoxie>
    <el-card class="box-card" >
      <el-row>
        <el-col :span="8">
          <el-input 
            v-model="usersParams.query"
            :clearable="true"
            placeholder="请输入内容"
            @clear="getUsersList"
            >        
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table
        border
        :data="userList"
        style="width: 100%;margin-top:10px;margin-bottom:20px"
      >
        <el-table-column type="index" lable="序号"></el-table-column>
        <el-table-column prop="username" label="用户名" width="180"></el-table-column>
        <el-table-column prop="role_name" label="角色名称" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mg_state" label="状态" width="180">
          <template slot-scope="scoped">
            <div>
              <el-switch v-model="scoped.row.mg_state" @change="userStateChange(scoped.row)"></el-switch>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作"  width="180">
          <template slot-scope="scoped">
            <div>
              <el-tooltip content="修改用户信息" placement="top-start">
                <el-button type="primary" icon="el-icon-edit" circle @click="editShowDialog(scoped.row)"></el-button>
              </el-tooltip>
              <el-tooltip content="删除用户信息" placement="top-start">
                <el-button type="danger" icon="el-icon-delete" circle @click="deletUserInfoByid(scoped.row.id)"></el-button>
              </el-tooltip>
              <el-tooltip content="权限分配" placement="top-start">
                <el-button type="warning" icon="el-icon-setting" circle></el-button>
              </el-tooltip>  
            </div>
          </template>       
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="usersParams.pagenum"
        :page-sizes="[1,2,5,8]"
        :page-size="usersParams.pagesize"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total"
      >
      </el-pagination>
      <el-dialog
        title="添加用户"
        :visible.sync = "addDialogVisible"
        width="30%"
        @close="addUserDialogClear"
      >
        <el-form
          :model="addUserForm"
          :rules="addUserFormRules"
          ref="addUserFormRef"
          label-width="100px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </span>
      </el-dialog>

      <el-dialog
        title="修改用户信息"
        :visible.sync = "editDialogVisible"
        width="30%"
      >
        <el-form
          :model="editFormData"
          ref="editForm"
          label-width="80px"
        >
          <el-form-item label="用户名">
            <el-input v-model="editFormData.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email" :rules="addUserFormRules.email">
            <el-input v-model="editFormData.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile" :rules="addUserFormRules.mobile">
            <el-input v-model="editFormData.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editUserInfo">修改用户信息</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import mianbaoxie from "@/compoents/mianbaoxie";
import { users_list_req,users_state_req,add_user_req,users_info_id_req,edit_users_infi_req,delete_users_req } from "@/api/users.js";
export default {
  created(){
    const userParamsS = JSON.parse(sessionStorage.getItem("usersParams"));
    if(userParamsS){
      this.usersParams = userParamsS;
    }else{
      this.usersParams = {
        query:"",
        pagenum:1,
        pagesize:5,
      };
    }
  },
  data(){
    let checkEmail = (rule,value,callback)=>{
      const emailReg = /^\w+@\w+(\.\w+)+$/;
      if(emailReg.test(value)){
        return callback();
      }
      return callback(new Error("请输入合法邮箱"));

    };
    let checkMobile = (rule,value,callback) =>{
      const mobileReg = /^1[3456789]\d{9}$/;
      if(mobileReg.test(value)){
        return callback();
      }
      callback(new Error("请输入合法的手机号"));
    }
    return{
      usersParams:{},
      userList:[],
      total:0,
      addDialogVisible:false,
      addUserForm:{
        username:"",
        password:"",
        email:"",
        mobile:"",
      },
      addUserFormRules:{
        username:[
          {required:true, message:"请输入用户名",trigger:"blur"},
          {
            min:3,
            max:10,
            message:"长度在3到10个字符",
            trigger:"blur",
          },
        ],
        password:[
          {required:true, message:"请输入密码",trigger:"blur"},
          {
            min:3,
            max:12,
            message:"长度在3~12个字符",
            trigger:"blur",
          },
        ],
        email:[
          {required:true,message:"请输入邮箱",trigger:"blur"},
          {
            validator:checkEmail,
            trigger:"blur",
          },
        ],
        mobile:[
          {required:true,message:"请输入电话",trigger:"blur"},
          {
            validator:checkMobile,
            trigger:"blur",
          },
        ],
      },
      editDialogVisible:false,
      editFormData:{},
    };
  },
  components: {
    mianbaoxie,
  },
  mounted(){
    this.getUsersList();
  },
  methods:{
    async getUsersList(){
      const result = await users_list_req({
        methods:"get",
        url:"users",
        params:this.usersParams,
      });
      if(result.meta.status == 200){
        this.userList = result.data.users;
        this.total = result.data.total;
      }
    },
    handleSizeChange(newPageSize){
      this.usersParams.pagesize = newPageSize;
      sessionStorage.setItem("usersParams", JSON.stringify(this.usersParams));
      this.getUsersList();
    },
    handleCurrentChange(newPageNum){
      this.usersParams.pagenum = newPageNum;
      sessionStorage.setItem("usersParams", JSON.stringify(this.usersParams));
      this.getUsersList();
    },
    async userStateChange(newState){
      console.log(newState);
      const result = await users_state_req({
        method:"put",
        url:`users/${newState.id}/state/${newState.mg_state}`,
      });
      console.log(result);
      if (result.meta.status != 200 ){
        newState.mg_state = !newState.mg_state;
        return this.$message.error("更新用户状态失败");
      }
      return this.$message({
        type:"success",
        message:"更新用户状态成功",
      });
    },
    addUser(){
      this.$refs.addUserFormRef.validate(async(valid) =>{
        if(!valid) return;
        const result = await add_user_req({
          method:"post",
          url:"users",
          data:this.addUserForm,
        });
        if(result.meta.status != 201){
          return this.$message.error("添加用户失败");
        }
        this.addDialogVisible = false;
        this.getUsersList();
        return this.$message.success("添加用户成功");
      });
    },
    addUserDialogClear(){
      this.$refs.addUserFormRef.resetFields();
    },
    async editShowDialog(userInfo){
      const result = await users_info_id_req({
        method:"get",
        url:`users/${userInfo.id}`,
      });
      if(result.meta.status !== 200){
        return this.$message.error("查询数据失败");

      }
      this.editFormData = result.data;
      this.editDialogVisible = true;
    },
    editUserInfo(){
      this.$refs.editForm.validate(async(valid)=>{
        if(!valid) return;
        const result = await edit_users_infi_req({
          method:"put",
          url:`users/${this.editFormData.id}`,
          data:this.editFormData,
        });
        if(result.meta.status !== 200){
          return this.$message.error("修改用户信息成功");
          
        }
        this.getUsersList();
        this.editDialogVisible = false;
        return this.$message.success("修改用户信息成功");

      });
    },
    async deletUserInfoByid(id){
      const resultConfirm = await this.$confirm(
        "此操作将永久删除该用户，是否继续？",
        "提示",
        {
          confirmButtonText:"确定",
          cancelButtonText:"取消",
          type:"warning",
        }
      ).catch((err)=> err);
      if(resultConfirm == "confirm"){
        const result = await delete_users_req({
          method:"delete",
          url:`users/${id}`,
        });
        if(result.meta.status != 200){
          return this.$message.error("用户删除失败");
        }
        this.$message.success("用户删除成功");
        this.getUsersList();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.users-box{
  display: flex;
  flex-direction: column,
}
</style>